/**
 * RunTask.java
 * com.sitech.dmcs.core
 * Function： TODO 
 *
 *   ver  author   date    
 * ──────────────────────────────────
 *   	 geutopia  Jan 25, 2011        
 *
 * Copyright (c) 2011, TNT All Rights Reserved.
 */

package com.sitech.timing;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.sitech.timing.TimingConst;
import com.sitech.timing.domain.GroupTaskInfo;
import com.sitech.timing.param.ParamService;
import com.sitech.timing.dao.TaskDao;
import com.sitech.timing.domain.TaskInstance;
import com.sitech.timing.domain.TaskResult;

/**
 * ClassName:RunTask Function: TODO ADD FUNCTION Reason: TODO ADD REASON
 * 
 * @author geutopia
 * @version
 * @since Ver 1.1
 * @Date 2011 Jan 25, 2011 4:37:51 PM
 * 
 * @see
 */

public class RunTask implements Runnable
{
	private static final Log log = LogFactory.getLog(RunTask.class);

	private Task task;
	private TaskInstance taskInstance;
	private Map<String, Object> paramMap;
	private GroupTaskManager groupTaskManager;
	private TaskDao taskDao;
	private ParamService paramService;

	public RunTask(Task task, TaskInstance taskInstance, Map<String, Object> paramMap,
			GroupTaskManager groupTaskManager, TaskDao taskDao, ParamService paramService)
	{
		this.task = task;
		this.taskInstance = taskInstance;
		this.paramMap = paramMap;
		this.groupTaskManager = groupTaskManager;
		this.taskDao = taskDao;
		this.paramService = paramService;
	}

	public void run()
	{
		log.debug("Run Task: GroupTaskId = " + taskInstance.getGroupTaskId() + " TaskId = " + taskInstance.getTaskId()
				+ " GroupTaskInstanceId = " + taskInstance.getGroupTaskInstanceId()
				+ " TaskInstanceid = " + taskInstance.getTaskInstanceId() );
		try
		{
			GroupTaskInfo groupTaskInfo =GroupTaskContext.getGroupTaskInfo(taskInstance.getGroupTaskId());
			if(StringUtils.isNotEmpty(groupTaskInfo.getRunType())&&
					TimingConst.GROUPTASK_RUNTYPE_MANUAL.equals(groupTaskInfo.getRunType())){
				Date date = new Date();
				SimpleDateFormat simpleDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				groupTaskInfo.setRunTrigger(simpleDate.format(date)); 
			}
			TaskResult taskResult = task.runTask(paramMap, taskInstance);
			paramService.insertResult(taskInstance, taskResult);
			if (taskResult == null || taskResult.getTaskStatus() == null
					|| !taskResult.getTaskStatus().equals(TimingConst.TASK_STATUS_PAUSE))
			{
				groupTaskManager.generateTask(taskInstance);
				GroupTaskContext.taskEnd(taskInstance);
			}
		}
		catch (Throwable throwable)
		{
			log.error("GroupTask:" + taskInstance.getGroupTaskId() + "Task : " + taskInstance.getTaskId()
					+ "TaskInstanceId" + taskInstance.getTaskInstanceId() + "error!", throwable);
			GroupTaskContext.taskRunError(taskInstance);
		}
	}

}
